package com.atguigu.gulimall.Auth.Controller;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class SmsSendCode {

   @Autowired
    StringRedisTemplate redisTemplate;

   @ResponseBody
   @RequestMapping("/sms/sendCode")
   public R sendCode(@RequestParam(value = "phone",required = false) long phone){


       String codeByRedis = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
       if(codeByRedis==null||"".equals(codeByRedis)){
           String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
           redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,5, TimeUnit.MINUTES);
           return R.ok();
       }

       // 防止前端 60秒内再次请求 验证码
       long oldTime = Long.parseLong(codeByRedis.split("_")[1]);
        if(System.currentTimeMillis()-oldTime<60000){
            return R.error(BizCodeEnume.SMS_FREQUENCYCODE_EXCEPTION.getCode(),BizCodeEnume.SMS_FREQUENCYCODE_EXCEPTION.getMsg());
        }
       return R.ok();
   }



}
